package org.jeecg.modules.manager.controller;

import java.util.*;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.swing.text.html.Option;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.google.common.collect.Maps;
import me.zhyd.oauth.utils.StringUtils;
import me.zhyd.oauth.utils.UuidUtils;
import org.apache.poi.ss.formula.functions.T;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.checkerframework.checker.nullness.Opt;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.util.RedisUtil;
import org.jeecg.common.util.UUIDGenerator;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.manager.entity.*;
import org.jeecg.modules.manager.mapper.GoodsTypeMapper;
import org.jeecg.modules.manager.service.ICarInfoService;
import org.jeecg.modules.manager.service.ICarService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;

import org.quartz.spi.ThreadExecutor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

 /**
 * @Description: 汽车表
 * @Author: jeecg-boot
 * @Date:   2021-11-19
 * @Version: V1.0
 */
@Slf4j
@Api(tags="汽车表")
@RestController
@RequestMapping("/manager/car")
public class CarController extends JeecgController<Car, ICarService> {
	@Autowired
	private ICarService carService;

	@Autowired
	private ICarInfoService carInfoService;

	@Autowired
	private GoodsTypeMapper goodsTypeMapper;

	 //封装了redis操作各种方法
	 @Autowired
	 private RedisUtil redisUtil;


	 @GetMapping(value = "/addTestData")
	 @Transactional(rollbackFor = Exception.class)
//	 @ApiOperation(value="汽车表-添加测试数据", notes="汽车表-添加测试数据")

	 public Result<T> addTestData(){
		 Thread thread = new Thread(this::addData);
		 Thread thread1 = new Thread(this::addData);
		 Thread thread2 = new Thread(this::addData);
		 Thread thread3 = new Thread(this::addData);
		 Thread thread4 = new Thread(this::addData);
		 thread.start();
		 thread1.start();
		 thread2.start();
		 thread3.start();
		 thread4.start();

		 return Result.OK();
	 }
	 public void addData(){
		 String[] split = "4028b29e7d4c0817017d4c0817960000,4028b29e7d4c0817017d4c08280b0001,4028b29e7d4c2436017d4c2436c40000".split(",");

		 //定义一些汽车品牌
		 String[] carBrand = ("比亚迪、奇瑞、吉利、长城、红旗、力帆、江淮、一汽、奔腾" +
				 "、海马、五菱、丰田、马自达、铃木、三菱、奥迪、奔驰、宝马、大众、保时捷、雪佛兰、别克、凯迪拉克、福特").split("、");
		 String[] color = "红，橙红，橙，橙黄，黄，黄绿，绿，蓝绿，蓝，蓝紫，紫，紫红".split("，");
		 String[] engine = "直列发动机、V型发动机、W型发动机、水平对置发动机".split("、");
		 String[] version = "标准版，舒适版，豪华版，运动版".split("，");
		 String[] transmission = "手动变速箱，amt变速箱，cvt变速箱，at变速箱，双离合变速箱".split("，");
		 Random random = new Random();
		 for (int i = 0; i < 1000; i++) {
			 String brand = carBrand[Math.max(0,random.nextInt(23))];
			 String carName = brand+random.nextInt(99999)+10000;
			 //构建车辆
			 Car build = Car.builder()
					 .carTypeId(split[random.nextInt(2)])
					 .deleted(DeletedEnum.FALSE)
					 .carBrand(brand)
					 .carId(UUIDGenerator.generate())
					 .carName(carName).createdBy(currentUser().getUsername()).createdTime(new Date()).build();
			 List<CarInfo> carInfos = new ArrayList<>();
			 //构建车辆信息 具体一辆车几条信息就随机了
			 for (int j = 0; j < random.nextInt(5)+1; j++) {
				 carInfos.add(CarInfo.builder().infoId(UUIDGenerator.generate())
						 .createdBy(currentUser().getUsername()).createdTime(new Date())
						 .deleted(DeletedEnum.FALSE)
						 .infoColor(color[random.nextInt(11)])
						 .infoEngine(engine[random.nextInt(3)])
						 .infoVersion(version[random.nextInt(3)])
						 .infoManufacturer(build.getCarBrand())
						 .parentId(build.getCarId())
						 .infoPrice(String.valueOf(random.nextInt(9999999)+100000))
						 .infoTransmission(transmission[random.nextInt(4)]).build());
			 }
			 build.setCarInfoList(carInfos);
			 carService.save(build);
			 build.getCarInfoList().forEach(
					 carInfo -> carInfoService.save(carInfo)
			 );
			 System.out.println("tianjia");
		 }
	 }

	 /**
	 * 分页列表查询x
	 *
	 * @param car
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@AutoLog(value = "汽车表-分页列表查询")
	@ApiOperation(value="汽车表-分页列表查询", notes="汽车表-分页列表查询")
	@GetMapping(value = "/list")
	public Result<?> queryPageList(Car car,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		QueryWrapper<Car> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("deleted",DeletedEnum.FALSE);
		Optional.ofNullable(car.getCarName()).ifPresent(s -> {
			queryWrapper.like("car_name",s);
		});
		Page<Car> page = new Page<Car>(pageNo, pageSize);
		IPage<Car> pageList = carService.page(page, queryWrapper);
		return Result.OK(pageList);
	}

	/**
	 * 添加
	 *
	 * @param car
	 * @return
	 */
	@AutoLog(value = "汽车表-添加")
	@ApiOperation(value="汽车表-添加或修改", notes="汽车表-添加或修改")
	@PostMapping(value = "/addAndEdit")
	@Transactional(rollbackFor=Exception.class)
	public Result<?> addAndEdit(@RequestBody Car car) {
		List<CarInfo> carInfos = car.getCarInfoList();
		try{
			if (Optional.ofNullable(car.getCarId()).isPresent() && StringUtils.isNotEmpty(car.getCarId())){
				car.setUpdatedBy(currentUser().getUsername());
				car.setUpdatedTime(new Date());
				carService.updateById(car);
				//修改汽车信息
				carInfos.forEach(carInfo -> {
					carInfo.setUpdatedBy(currentUser().getUsername());
					carInfo.setUpdatedTime(new Date());
					carInfoService.updateById(carInfo);
				});
				return Result.OK("修改成功！");
			}else {
				//新增汽车
				car.setCarId(UUIDGenerator.generate());
				car.setDeleted(DeletedEnum.FALSE);
				car.setCreatedBy(currentUser().getUsername());
				car.setCreatedTime(new Date());
				carService.save(car);
				if(carInfos.size() < 1){
					return Result.error("添加失败！必须有一条汽车信息！");
				}
				//新增汽车信息
				carInfos.forEach(carInfo -> {
					carInfo.setDeleted(DeletedEnum.FALSE);
					carInfo.setCreatedBy(currentUser().getUsername());
					carInfo.setCreatedTime(new Date());
					carInfo.setInfoId(UUIDGenerator.generate());
					carInfo.setParentId(car.getCarId());
					carInfoService.save(carInfo);
				});
				if (redisUtil.get(car.getCarId()) != null){
					redisUtil.del(car.getCarId());
				}
				return Result.OK("添加成功！");
			}
		}catch (Exception e){
			e.printStackTrace();
			return Result.error("请求失败！检查参数！");
		}
	}


	/**
	 * 批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "汽车表-批量删除")
	@ApiOperation(value="汽车表-批量删除", notes="汽车表-批量删除")
	@PostMapping(value = "/deleteBatch")
	@Transactional(rollbackFor=Exception.class)
	public Result<?> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		return carService.removeIds(ids) == 1 ? Result.ok("删除成功"):Result.error("删除失败");
	}

	 /**
	  * 删除汽车信息
	  *
	  * @param ids
	  * @return
	  */
	 @AutoLog(value = "汽车表-批量删除")
	 @ApiOperation(value="汽车表-删除一条汽车信息", notes="汽车表-删除一条汽车信息")
	 @PostMapping(value = "/deleteCarInfo")
	 @Transactional(rollbackFor=Exception.class)
	 public Result<?> deleteCarInfo(@RequestParam(name="ids",required=true) String ids) {
		 return carService.removeCarInfo(ids) == 1 ? Result.ok("删除成功"):Result.error("删除失败");
	 }

	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "汽车表-通过id查询")
	@ApiOperation(value="汽车表-通过id查询", notes="汽车表-通过id查询")
	@GetMapping(value = "/queryById")

	public Result<?> queryById(@RequestParam(name="id",required=true) String id) {
		CarInfoVo car = (CarInfoVo) redisUtil.get(id);
		if (car != null){
			return Result.OK(car);
		}
		if (Optional.ofNullable(id).isPresent() && StringUtils.isNotEmpty(id)){
			car = carService.queryCarById(id);
			if (car != null){
				redisUtil.set(id,car);
			}
			return car != null ? Result.OK(car):Result.error("查询失败！结果可能为空");
		}
		return Result.error("id不能为空");
	}
	 /**
	  * 测试图片上传
	  */
	 @ApiOperation(value="汽车表-给汽车信息上传图片", notes="汽车表-给汽车信息上传图片")
	 @PostMapping(value = "/uploadImage")
	 @Transactional(rollbackFor=Exception.class)
	 public Result<?> uploadImage(@RequestParam(name="file",required=true) MultipartFile file,String carInfoId) {
		 String path = carService.uploadImage(file,carInfoId);
		 //如果path不为空则更新info的图片地址
		 if (Optional.ofNullable(path).isPresent() && StringUtils.isNotEmpty(path)) {
			 CarInfo carInfo = new CarInfo();
			 carInfo.setInfoId(carInfoId);
			 carInfo.setInfoImg(path);
			 boolean flag = carInfoService.updateById(carInfo);
			 //懒得改了我就取反了
			 return !flag ? Result.error("上传失败！"):Result.OK("上传成功！");
		 }
		 return Result.error("后台地址问题！上传文件失败！");
	 }
  /**
   * 导出excel
   *
   * @param request
   * @param car
   */
  @RequestMapping(value = "/exportXls")
  public ModelAndView exportXls(HttpServletRequest request, Car car) {
      return super.exportXls(request, car, Car.class, "汽车表");
  }

  /**
   * 通过excel导入数据
   *
   * @param request
   * @param response
   * @return
   */
  @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
  public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
      return super.importExcel(request, response, Car.class);
  }

}
